import React, { useState, useEffect } from 'react';
import { useNavigate, useLocation, Outlet } from 'react-router-dom';
import {
  HomeOutlined,
  MailOutlined,
  TeamOutlined,
  UserOutlined,
  GiftOutlined,
  MoneyCollectOutlined,
  PictureOutlined,
  FileTextOutlined,
  TrophyOutlined,
  ToolOutlined,
  SolutionOutlined,
  SettingOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  LogoutOutlined,
  KeyOutlined,
} from '@ant-design/icons';
import { Button, Menu, Layout, Dropdown, Avatar, Space, Modal, Form, Input, message } from 'antd';
import { _apiChangePassword, _apiCurrentUser } from '../../api/index';
const { Header, Sider, Content } = Layout;

const items = [
  {
    key: 'dashboard',
    icon: <HomeOutlined />,
    label: '首页',
  },
  {
    key: 'role',
    icon: <SolutionOutlined />,
    label: '角色管理',
  },
  {
    key: 'account',
    icon: <MailOutlined />,
    label: '账号管理',
  },
  
  // {
  //   key: 'distribution',
  //   icon: <TeamOutlined />,
  //   label: '分店管理',
  // },
  {
    key: 'member',
    icon: <UserOutlined />,
    label: '会员管理',
  },
  {
    key: 'rechargeAudit',
    icon: <UserOutlined />,
    label: '充值审核',
  },
  {
    key: 'products',
    icon: <GiftOutlined />,
    label: '商品管理',
    children: [
      {
        key: 'categories',
        label: '商品分类'
      },
      {
        key: 'productList',
        label: '商品列表'
      }
    ]
  },
  {
    key: 'order',
    icon: <GiftOutlined />,
    label: '订单管理',
  },
  {
    key: 'assets',
    icon: <ToolOutlined />,
    label: '资产管理',
  },
    {
    key: 'points',
    icon: <TrophyOutlined />,
    label: '积分管理',
  },
  // {
  //   key: 'invitation',
  //   icon: <MoneyCollectOutlined />,
  //   label: '邀请返现',
  // },
  // {
  //   key: 'banner',
  //   icon: <PictureOutlined />,
  //   label: 'banner管理',
  // },
  // {
  //   key: 'article',
  //   icon: <FileTextOutlined />,
  //   label: '文章管理',
  // },
    

  
];

function AdminDashboard() {
  const [collapsed, setCollapsed] = useState(false);
  const navigate = useNavigate();
  const location = useLocation();
  const [isPasswordModalVisible, setIsPasswordModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [userInfo, setUserInfo] = useState({});

  useEffect(() => {
    const fetchUserInfo = async () => {
      try {
        const response = await _apiCurrentUser();
        if (response && response.data) {
          setUserInfo(response.data);
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
      }
    };

    fetchUserInfo();
  }, []);

  const toggleCollapsed = () => {
    setCollapsed(!collapsed);
  };

  const handleMenuClick = ({ key }) => {
    navigate(`/admin/${key}`);
  };

  // 处理用户菜单点击
  const handleUserMenuClick = ({ key }) => {
    if (key === 'logout') {
      localStorage.removeItem('token');
      navigate('/login');
    } else if (key === 'changePassword') {
      setIsPasswordModalVisible(true);
    }
  };

  // 处理密码修改提交
  const handlePasswordSubmit = async (values) => {
    try {
      await _apiChangePassword({
        password: values.currentPassword,
        newPassword: values.newPassword,
        confirmPassword: values.confirmPassword
      });
      
      alert('密码修改成功，请重新登录');
      setIsPasswordModalVisible(false);
      form.resetFields();
      localStorage.removeItem('token');
      navigate('/login');
      
    } catch (error) {
      console.error('密码修改错误:', error);
      alert(error.response?.data?.message || '密码修改失败，请重试');
    }
  };

  // 用户下拉菜单项
  const userMenuItems = [
    {
      key: 'changePassword',
      icon: <KeyOutlined />,
      label: '修改密码'
    },
    {
      key: 'logout',
      icon: <LogoutOutlined />,
      label: '退出登录'
    }
  ];

  return (
    <Layout style={{ minHeight: '100vh' }}>
      <Sider trigger={null} collapsible collapsed={collapsed}>
        <div style={{ height: 32, margin: 16, background: 'rgba(255, 255, 255, 0.2)' }} />
        <Menu
          selectedKeys={[location.pathname.split('/').pop() || 'dashboard']}
          mode="inline"
          theme="dark"
          items={items}
          onClick={handleMenuClick}
        />
      </Sider>
      <Layout>
        <Header 
          style={{ 
            padding: '0 16px', 
            background: '#fff', 
            display: 'flex', 
            justifyContent: 'space-between', 
            alignItems: 'center' 
          }}
        >
          <Button
            type="text"
            icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
            onClick={toggleCollapsed}
            style={{
              fontSize: '16px',
              width: 64,
              height: 64,
            }}
          />
          <Dropdown
            menu={{
              items: userMenuItems,
              onClick: handleUserMenuClick
            }}
          >
            <Space style={{ cursor: 'pointer' }}>
              <Avatar 
                src={userInfo.avatar} 
                icon={!userInfo.avatar && <UserOutlined />}
                style={{ 
                  backgroundColor: !userInfo.avatar ? '#1890ff' : 'transparent',
                }}
              />
              <span>{userInfo.realName || '管理员'}</span>
            </Space>
          </Dropdown>
        </Header>
        <Content
          style={{
            margin: '24px 16px',
            padding: 24,
            minHeight: 280,
            background: '#fff',
          }}
        >
          <Outlet />
        </Content>
      </Layout>
      <Modal
        title="修改密码"
        open={isPasswordModalVisible}
        onCancel={() => {
          setIsPasswordModalVisible(false);
          form.resetFields();
        }}
        footer={null}
      >
        <Form
          form={form}
          onFinish={handlePasswordSubmit}
          layout="vertical"
        >
          <Form.Item
            name="currentPassword"
            label="当前密码"
            rules={[{ required: true, message: '请输入当前密码' }]}
          >
            <Input.Password />
          </Form.Item>
          <Form.Item
            name="newPassword"
            label="新密码"
            rules={[
              { required: true, message: '请输入新密码' },
              { min: 6, message: '密码长度不能少于6位' }
            ]}
          >
            <Input.Password />
          </Form.Item>
          <Form.Item
            name="confirmPassword"
            label="确认新密码"
            dependencies={['newPassword']}
            rules={[
              { required: true, message: '请确认新密码' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('newPassword') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('两次输入的密码不一致'));
                },
              }),
            ]}
          >
            <Input.Password />
          </Form.Item>
          <Form.Item style={{ marginBottom: 0, textAlign: 'right' }}>
            <Space>
              <Button onClick={() => {
                setIsPasswordModalVisible(false);
                form.resetFields();
              }}>
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                确认
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </Layout>
  );
}

export default AdminDashboard;